<template>
	<view class="address-edit">
		<form @submit="formSubmit" report-submit="true">
			<view class="form bg-white">
				<view class="form-item row">
					<view class="label">收货人</view>
					<input class="ml10" v-model="addressObj.contact" name="contact" type="text"
						placeholder="请填写收货人姓名" />
				</view>
				<view class="form-item row">
					<view class="label">联系方式</view>
					<input class="ml10" name="telephone" v-model="addressObj.telephone" type="number"
						placeholder="请填写手机号码"></input>
				</view>
				<view @click="showRegion = true">
					<view class="form-item row">
						<view class="label">所在地区</view>
						<input class="ml10" name="region" v-model="region" disabled type="text"
							placeholder="请选择省、市、区"></input>
						<image class="icon-sm ml10" src="/static/images/arrow_right.png" />
					</view>
				</view>
				<view>
					<u-field v-model="addressObj.address" type="textarea" label="详细地址" placeholder="请填写小区、街道、门牌号等信息"
						:field-style="{flex: 1, 'margin-left': '20rpx', height: '160rpx'}" />
					<!-- <view class="form-item row" style="height: 200rpx;">					 -->
					<!-- <view class="label mt20" style="align-self: flex-start;">详细地址</view> -->
					<!-- <textarea name="address" style="height: 160rpx;padding: 20rpx 20rpx 20rpx 30rpx;" v-model="addressObj.address"  @input="textareaChange" placeholder="请填写小区、街道、门牌号等信息" auto-blur /> -->
					<!-- </view> -->
				</view>
				<view class="form-item row" @tap="choosePosti">
					<view class="label">
						精准位置
					</view>
					<view class="row-between flex1">
						<view class="line1" style="padding-left: 10rpx;max-width: calc(100vw - 280rpx);">
							纬度:{{addressObj.location.lat || '无'}}
							&nbsp;&nbsp;
							经度:{{addressObj.location.lng || '无'}}
						</view>
						<view>
							<u-icon name="map-fill" color="var(--primary-color)" size="36"></u-icon>
						</view>
					</view>
				</view>
				<view>
					<u-field type="textarea" placeholder="填入文本自动解析填写地址" label-width="0" trim :border-bottom="false"
						:clearable="CSSFontPaletteValuesRule" v-model="recogniteAddress"
						:field-style="{backgroundColor:'#eee',borderRadius:'20rpx',padding:'6rpx 10rpx'}">
					</u-field>
					<view class="row-end" style="padding-right: 60rpx;padding-bottom: 30rpx;">
						<u-button type="default" shape="circle" size="mini" class="mr20"
							@click="recogniteAddress='';">清空</u-button>
						<u-button type="primary" shape="circle" size="mini" @click="recognite">识别地址</u-button>
					</view>
				</view>
			</view>
			<view class="mt10 mb10 bg-white check-wrap">
				<radio-group class="row" @click="ChangeIsDefault">
					<radio id="checkbox" style="border-radius: 50%;transform:scale(0.7)"
						:checked="addressObj.is_default ? true : false" color="#24A3FF" />
					<label for="checkbox">
						<text>设置为默认</text>
					</label>
				</radio-group>
			</view>
			<button class="my-btn bg-primary white br60" form-type="submit"
				style="background-color: #24A3FF;">完成</button>
			<template v-if="isModifyAddress">
				<u-modal id="delete-dialog" v-model="isDelAddressPop" :showCancelButton="true" confirm-text="确认"
					confirm-color="#24A3FF" :show-title="false" @confirm="handleDelAddress"
					@cancel="isDelAddressPop = false">
					<view class="column-center tips-dialog">
						<!-- <image class="icon-lg" src="/static/images/icon_warning.png"></image> -->
						<u-icon name="error-circle-fill" color="#24A3FF" size="56" />
						<view style="margin-top:30rpx">确认删除该地址吗？</view>
					</view>
				</u-modal>
				<button class="my-btn bg-white normal br60" style="border: 1rpx solid #D7D7D7;"
					@tap="isDelAddressPop = true">删除该收货地址</button>
			</template>
		</form>
		<u-select v-model="showRegion" mode="mutil-column-auto" @confirm="regionChange" :list="lists"></u-select>
	</view>
</template>

<script>
	import {
		editAddress,
		getOneAddress,
		hasRegionCode,
		addAddress,
		delAddress,
		postRecogniteAddress,
	} from '@/api/user';
	import area from '@/utils/area'
	export default {
		data() {
			return {
				isModifyAddress: false, // 判断是否为修改地址
				isDelAddressPop: false, // 删除地址 -> 弹窗
				addressObj: {
					contact: '',
					telephone: '',
					location: null,
					province: '',
					city: '',
					district: '',
					address: '',
					is_default: 0
				},
				recogniteAddress: '',
				region: '',
				addressId: '',
				defaultRegion: ['广东省', '广州市', '番禺区'],
				defaultRegionCode: '440113',
				showRegion: false,
				lists: []
			};
		},
		props: {},

		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			this.addressId = parseInt(options.id)
			if (options.id) {
				uni.setNavigationBarTitle({
					title: '编辑地址'
				});
				this.isModifyAddress = true;
				this.getOneAddressFun();
			} else {
				uni.setNavigationBarTitle({
					title: '添加地址'
				});
				this.getWxAddressFun();
			}
			this.$nextTick(() => {
				this.lists = area
			})
		},

		/**
		 * 生命周期函数--监听页面卸载
		 */
		onUnload: function() {
			uni.removeStorageSync('wxAddress');
		},

		/**
		 * 用户点击右上角分享
		 */
		onShareAppMessage: function() {},
		methods: {
			recognite() {
				const text = this.recogniteAddress;
				postRecogniteAddress({
					address: text
				}).then(res => {
					if (res.code != 1) return;
					this.addressObj.contact = res.data.name;
					this.addressObj.telephone = res.data.mobile;
					this.region = res.data.sheng;
					const sheng = res.data.sheng.split('-');
					this.addressObj.province = sheng[0];
					const province_data = area.find(v => v.label == sheng[0]);
					this.addressObj.province_id = province_data.value;
					this.addressObj.city = sheng[1];
					const city_data = province_data.children.find(v => v.label == sheng[1]);
					this.addressObj.city_id = city_data.value;
					this.addressObj.district = sheng[2];
					const district_data = city_data.children.find(v => v.label == sheng[2]);
					this.addressObj.district_id = district_data.value;
					this.addressObj.address = res.data.address;
				})
			},
			choosePosti() {
				if (!this.region) return this.$toast({
					title: '请填写所在地区'
				})
				if (!this.addressObj.address) return this.$toast({
					title: '请填写详细地址'
				})
				this.QQMAPSDK.geocoder({
					address: this.region + this.addressObj.address,
					success: res => {
						uni.chooseLocation({
							latitude: res.result.location.lat,
							longitude: res.result.location.lng,
							success: res2 => {
								console.log(res2)
								if (res2.errMsg == 'chooseLocation:ok') {
									this.$set(this.addressObj, 'location', {
										lat: res2.latitude,
										lng: res2.longitude
									})
								}
							},
							fail: err => {
								console.log(err)
								this.$toast({
									title: '选择失败'
								})
							}
						})
					},
					fail: err => {
						console.log(err)
						this.$toast({
							title: '腾讯地图接口发生错误，请联系开发人员'
						})
					}
				})
			},
			formSubmit(e) {
				let {
					value
				} = e.detail;
				let {
					addressObj: {
						province_id,
						city_id,
						district_id,
						is_default,
						address
					},
					addressId
				} = this;
				value.address = address;
				if (!value.contact) return this.$toast({
					title: '请填写收货人姓名'
				});
				if (!value.telephone) return this.$toast({
					title: '请填写手机号码'
				});
				if (!value.region) return this.$toast({
					title: '请选择省、市、区'
				});
				if (!value.address) return this.$toast({
					title: '请填写小区、街道、门牌号等信息'
				});
				if (!this.addressObj.location) return this.$toast({
					title: '请选择位置'
				});
				value.province_id = parseInt(province_id);
				value.city_id = parseInt(city_id);
				value.district_id = parseInt(district_id);
				value.is_default = is_default;
				value.id = addressId;
				value.lat = this.addressObj.location.lat;
				value.lng = this.addressObj.location.lng;
				delete value.region;

				if (addressId) {
					editAddress(value).then(res => {
						if (res.code == 1) {
							this.$toast({
								title: res.msg
							}, {
								tab: 3,
								url: 1
							});
						}
					}).catch(err => {
						return this.$toast({
							title: err
						});
					});
				} else {
					addAddress(value).then(res => {
						if (res.code == 1) {
							this.$toast({
								title: res.msg
							}, {
								tab: 3,
								url: 1
							});
						}
					}).catch(err => {
						return this.$toast({
							title: err
						});
					});
				}
			},
			regionChange(region) {
				this.addressObj.province_id = region[0].value;
				this.addressObj.city_id = region[1].value;
				this.addressObj.district_id = region[2].value;
				this.region = region[0].label + " " + region[1].label + " " + region[2].label
			},

			ChangeIsDefault: function(e) {
				if (this.addressObj.is_default == 0) {
					this.addressObj.is_default = 1;
				} else {
					this.addressObj.is_default = 0;
				}
			},

			textareaChange: function(e) {
				this.addressObj.address = e.detail.value;
			},

			getOneAddressFun() {
				getOneAddress(this.addressId).then(res => {
					if (res.code == 1) {
						let {
							city,
							province,
							district,
						} = res.data;
						this.addressObj = res.data;
						this.$set(this.addressObj, 'location', {
							lat: res.data.lat,
							lng: res.data.lng,
						})
						this.region = `${province} ${city} ${district}`
					}
				});
			},

			getWxAddressFun() {
				let wxAddress = uni.getStorageSync('wxAddress');
				if (!wxAddress) return;
				wxAddress = JSON.parse(wxAddress)
				let {
					userName: contact,
					telNumber: telephone,
					provinceName: province,
					cityName: city,
					detailInfo: address
				} = wxAddress;
				let district = wxAddress.countryName || wxAddress.countyName
				hasRegionCode({
					province,
					city,
					district
				}).then(res => {
					if (res.code == 1) {
						if (res.data.province) {
							this.region = `${province} ${city} ${district}`;
							this.addressObj.contact = contact;
							this.addressObj.telephone = telephone
							this.addressObj.address = address
							this.addressObj.province_id = res.data.province;
							this.addressObj.city_id = res.data.city;
							this.addressObj.district_id = res.data.district;
						}
					}
				});
			},

			// 删除地址
			handleDelAddress() {
				const id = this.addressId;
				console.log(id);
				delAddress(id).then(res => {
					if (res.code == 1) {
						this.$toast({
							title: res.msg
						});
						this.isDelAddressPop = false;
						uni.navigateBack(1);
					}
				});
			}

		}
	};
</script>

<style lang="scss">
	.address-edit {
		padding-top: 10rpx;

		.form {
			flex: 1;

			.form-item {
				padding: 0 24rpx;
				height: 80rpx;
				border-bottom: 1rpx solid #F2F2F2;
				overflow: hidden;

				.label {
					width: 150rpx;
				}

				input {
					height: 100%;
					flex: 1;
				}
			}
		}

		.check-wrap {
			padding: 20rpx;
		}

		.my-btn {
			margin: 30rpx 26rpx;
			text-align: center;
		}
	}

	van-field view {
		height: 100%;
	}

	van-field textarea {
		height: 100% !important;
		padding-top: 10rpx !important;
	}

	.van-cell {
		padding: 20rpx !important;
	}

	.van-field__body--textarea,
	.van-field__input {
		margin-left: 15rpx;
	}

	.tips-dialog {
		height: 230rpx;
		width: 100%;
	}
</style>